package com.monitor.handle_exception.com.ex.util;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JsonUtil {

    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    static{
        // config
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }

    public static <T> String obj2String(T src){
        if (src == null){
            return null;
        }
        try {
            return src instanceof String ? (String)src :objectMapper.writeValueAsString(src);
        } catch (IOException e) {
            log.warn("Object to String exception,error{} ",e);
            return null;
        }
    }

    public static <T> T string2Object(String string, TypeReference<T> typeReference){
        if (string == null || typeReference == null){
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? string : objectMapper.readValue(string, typeReference));
        } catch (IOException e) {
            log.warn("String: {} to Object: {} exception",string,typeReference.getType(),e);
            return null;
        }
    }
}
